<template>
	<view class="waterfall-wrapper">
		<view class="waterfall-column" v-for="(col, colIndex) in columns" :key="colIndex">
			<view v-for="(item, index) in col" :key="index" class="waterfall-item">
				<!-- 使用插槽自定义商品 -->
				<slot :item="item">
					<!-- 默认渲染，如果用户没有提供 slot -->
					<image :src="item.image" mode="widthFix" style="width: 100%; border-radius: 6px;"
						@load="e => imgLoadHandler(e, item)"></image>
				</slot>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		onMounted,
		nextTick
	} from 'vue'

	const props = defineProps({
		list: {
			type: Array,
			default: () => []
		},
		columnCount: {
			type: Number,
			default: 2
		},
		gap: {
			type: Number,
			default: 10
		}
	})

	const columns = ref([])

	const calculateColumns = () => {
		const cols = Array.from({
			length: props.columnCount
		}, () => [])
		const colHeights = Array.from({
			length: props.columnCount
		}, () => 0)

		props.list.forEach(item => {
			let height = item.height || 200
			if (item.width && item.height) {
				const screenWidth = uni.getSystemInfoSync().windowWidth
				const colWidth = (screenWidth - props.gap * (props.columnCount + 1)) / props.columnCount
				height = item.height / item.width * colWidth
			}

			// 找最短列
			let minIndex = 0
			let minHeight = colHeights[0]
			for (let i = 1; i < colHeights.length; i++) {
				if (colHeights[i] < minHeight) {
					minIndex = i
					minHeight = colHeights[i]
				}
			}

			cols[minIndex].push(item)
			colHeights[minIndex] += height + props.gap
		})

		columns.value = cols
	}

	/**
	 * 图片加载完成回调
	 * @param {Event} e 图片 load 事件
	 * @param {Object} item 对应的商品数据
	 */
	const imgLoadHandler = (e, item) => {
		const {
			width,
			height
		} = e.detail
		const screenWidth = uni.getSystemInfoSync().windowWidth
		const colWidth = (screenWidth - props.gap * (props.columnCount + 1)) / props.columnCount
		item.renderHeight = height / width * colWidth
		nextTick(() => calculateColumns())
	}

	watch(() => props.list, () => {
		nextTick(() => calculateColumns())
	}, {
		immediate: true
	})
</script>

<style scoped>
	.waterfall-wrapper {
		display: flex;
		justify-content: space-between;
		width: inherit;
	}

	.waterfall-column {
		/* flex: 1; */
		display: flex;
		flex-direction: column;
		gap: 10px;
		width: 48%;
	}

	.waterfall-column:not(:first-child) {
		margin-left: 10px;
	}

	.waterfall-item {
		/* item 样式可由插槽自定义 */
		width: 100%;
	}
</style>